#include "fxcc/imgui/FileSystemLayer.h"

void fxcc::imgui::FileSystemLayer::ProcessDir(Dir* dir)
{
    m_DirMap[dir->m_RelativePath] = dir;
    for (auto childDir : dir->m_Dirs)
    {
        ProcessDir(childDir.get());
    }
}

void fxcc::imgui::FileSystemLayer::SetDirPath(const std::string& dirPath)
{
    if (m_DirMap.find(dirPath) != m_DirMap.end())
    {
        m_SelectedDir = m_DirMap[dirPath];
        m_ChangeFlag = true;
    }
}

fxcc::imgui::FileSystemLayer::FileSystemLayer(const std::string& dirPath)
    :fxcc::imgui::Layer("File System Layer")
{
    m_Dir = std::make_shared<fxcc::Dir>(dirPath);
    m_CurrentDir = m_Dir.get();
    m_SelectedDir = m_CurrentDir;

    m_DirMap.clear();
    ProcessDir(m_Dir.get());

}

void fxcc::imgui::FileSystemLayer::ViewFunc()
{

}

void fxcc::imgui::FileSystemLayer::HandleSelection()
{
    m_CurrentDir->UnSelecteAll();

    for (auto it : m_CurrentDir->m_Dirs)
    {
        if (ItemInSelectionRange(it.get()))
        {
            it->m_Selected = true;
        }
    }

    for (auto it : m_CurrentDir->m_Files)
    {
        if (ItemInSelectionRange(it.get()))
        {
            it->m_Selected = true;
        }
    }
}

void fxcc::imgui::FileSystemLayer::HandleFunc()
{
    if (m_ChangeFlag)
    {
        m_CurrentDir->UnSelecteAll();

        if (m_SelectedDir)
        {
            IntoChangeDir();
        }
        m_ChangeFlag = false;
    }
}


void fxcc::imgui::FileSystemLayer::IntoChangeDir()
{
    m_IndexDirs.clear();

    m_CurrentDir = m_SelectedDir;
    
    Dir* sep = m_CurrentDir;

    while (1)
    {
        if (sep == m_Dir.get())
            break;


        m_IndexDirs.push_back(sep);
        sep = sep->m_Parent;
    
    }

    m_IndexDirs.push_back(m_Dir.get());

    std::reverse(m_IndexDirs.begin(), m_IndexDirs.end());
}


